from pydantic import BaseModel
import dataclasses
import pandas as pd
from ChartReport.Report import Report
from ChartReport.Template import Template, RenderContext
import pathlib
import uuid

g_current_path = pathlib.Path(__file__).parent.absolute()


@dataclasses.dataclass
class Model():
    df: pd.DataFrame
    x_field_name: str = 'x'
    y_field_name: str = 'y'


def _create_css_task(ctx: RenderContext, css_template: Template, css_file_name: str):
    if ctx:
        css_template.to_file(ctx.output_dir / css_file_name)


def create(model: Model, css_uuid='bar-chart', export_css_file=False) -> Template:
    id = css_uuid or uuid.uuid4()
    css_file = f'index-{id}.css'

    model.df = model.df.to_json(orient='records', force_ascii=False)

    main_tl = Template('./template.html')
    main_tl.template_base_path = g_current_path

    vars = dict(uuid=id, **model.__dict__)

    css = Template('./index.css')
    css.set_env_args(variable_start_string='>', variable_end_string='>')
    css.template_base_path = g_current_path
    css.set_vars(uuid=f'[data-{id}]')

    if export_css_file:
        css_file = f'index-{id}.css'
        vars.update(
            {'style_or_link': fr'<link rel="stylesheet" href="./{css_file}">'})
        main_tl.set_task(lambda ctx: _create_css_task(ctx, css, css_file))
    else:
        vars.update({'style_or_link': fr'<style>{css.render()}</style>'})

    main_tl.set_vars(**vars)

    return main_tl
